##    This file is part of The Most Awesome Story Ever
##
##    Foobar is free software: you can redistribute it and/or modify
##    it under the terms of the GNU General Public License as published by
##    the Free Software Foundation, either version 3 of the License, or
##    (at your option) any later version.
##
##    Foobar is distributed in the hope that it will be useful,
##    but WITHOUT ANY WARRANTY; without even the implied warranty of
##    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
##    GNU General Public License for more details.
##
##    You should have received a copy of the GNU General Public License
##    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.
##    
##    Copyright 2008, Ryan Michela

import wsgiref.handlers
import pagemodel
import pagerenderer
import pagemaker

from google.appengine.ext import webapp
from google.appengine.ext import db



class PageHandler(webapp.RequestHandler):
  """This class is the main class for loading, creating, and populating pages.

  The process flow for Pages is as follows:
  1. The user requests a page number (HTTP GET). If that page exists in the 
     Pages database, pagerenderer.renderPage() is called to render the form 
     to the response.
    
     If the page is not found, the user is redirected to page 1.
    
  2. The user enters a new option title on the requested page and clicks the
     Add New Option button in their browser. 
    
  3. A HTTP POST is processed with the action of newOption -- pagemaker.makePage() 
     is called to create a new page in the Pages database and the user is 
     forewarded to the new page.
    
  4. The user requests the new page (HTTP GET), but because it is empty, 
     pagerenderer.renderForm()is called to rendered a content entry form to 
     the output.
    
  5. The user fills out the page and submits a HTTP POST with the page contents
     and an action of editPage. The POST is processed and pagemaker.editPage()
     is called to populate the page contents in the Page database.
    
  6. The user is forewarded to the newly populated page and the cycle begins
     again at 1."""

  def get(self, pageNum):
    """Process a HTTP GET directive. Render either a page or a form from the
    Pages database."""
    #render the page. if the page doesn't exist, redirect to page 1
    page = self.queryPage(pageNum)
    if(page != None):
        if(page.isEmpty()):
            pagerenderer.renderForm(self.response, page.pageNum)
        else:
            pagerenderer.renderPage(self.response, page)
    else:
        self.redirect('/page1.html')


  def post(self, currentPageNum):
    """Process a HTTP POST directive. Create a new page or populate an existing
    page based on the "action" request parameter."""
    #figure out what postback is happening and dispatch accordingly
    action = self.request.get('action')
    if(action == 'newOption'):
        #add an option to this page and create a new page
        newPageOptionTitle = self.request.get('optionTitle')
        if(newPageOptionTitle != ''):
            newPageNum = pagemaker.makePage(newPageOptionTitle, 
                                                currentPageNum)
            #redirect to the new page
            self.redirect('/page%s.html' % newPageNum)
        else:
            #no option name given
            self.redirect('/page%s.html' % currentPageNum)
    elif(action == 'editPage'):
        #edit the contents of this page
        pageTitle = self.request.get('title')
        pageBody = self.request.get('body')
        pageImage = self.request.get('img')
        error = pagemaker.editPage(currentPageNum, pageTitle,
                                    pageBody, pageImage)
        if(error == None):
            #redirect to the current page to display it
            self.redirect('/page%s.html' % currentPageNum)
        else:
            #render the error
            pagerenderer.renderForm(self.response, currentPageNum, 
                                    error, pageTitle, pageBody)
    
    
  def queryPage(self, pageNum):
    """Fetch a page from the Pages database. Return the page or None if no
    page is found."""
    try:
        #querry the db for the current page
        pages = db.GqlQuery("SELECT * FROM Page WHERE pageNum = :1", 
                                int(pageNum))
        return pages[0]
    except:
        return None
    

def main():
  """Process all urls matching the pattern /page[#].html, passing in [#]
  as the second parameter to the get() and post() methods."""
  application = webapp.WSGIApplication([('/page(.*).html', PageHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
